import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @Author： yu.Tan
 * @Date: 2020/8/20 9:31
 * @Description:
 */
public class ConsumerRoutingA {
    private static final String EXCHANGE_NAME = "routing_exchange_direct";


    private static final String EXCHANGE_ROUTING_KEY = "info";

    private static final String QUEUE_NAME = "routing_direct_queue_name";

    public static void main(String[] args) {
        Connection connection = MQConnecitonUtils.getConnection();

        try {
            //创建消息通道
            final Channel channel = connection.createChannel();

            //创建队列
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);

            //将队列绑定到交换机上并指定routing_key
            channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, EXCHANGE_ROUTING_KEY);

            //同一时刻服务器只会发送一条消息给消费
            channel.basicQos(1);

            //创建消费者
            DefaultConsumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String msg = new String(body, "UTF-8");
                    System.out.println("【ConsumerRoutingA】receive message: " + msg);

                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        //消费完一条消息需要自动发送确认消息给MQ
                        channel.basicAck(envelope.getDeliveryTag(), false);
                    }
                }
            };
            //监听队列并关闭自动应答
            channel.basicConsume(QUEUE_NAME, false, consumer);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }
}
